package com.yjyw.tiexie.widget;

import android.content.Context;
import android.net.http.SslError;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * Created on 2019/7/14.
 *
 * @author ${AUTHOR}
 * TODO:
 */
public class AndroidWebView extends WebView {


    public AndroidWebView(Context context) {
        super(context);
        initView(context);
        this.setClickable(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptThirdPartyCookies(this, true);
        }
    }

    public AndroidWebView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        initView(context);
        this.setClickable(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptThirdPartyCookies(this, true);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        invalidate();
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private void initView(Context context) {
        setBackgroundColor(0);
        setHorizontalScrollBarEnabled(false);//水平不显示
        setVerticalScrollBarEnabled(false); //垂直不显示
        setDrawingCacheEnabled(false);
        getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);//不使用缓存
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        getSettings().setJavaScriptEnabled(true);
//        // 修改ua使得web端正确判断
//        String ua = getSettings().getUserAgentString();
//        getSettings().setUserAgentString(ua + "byton");
        // 自适应屏幕
//        getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
//        getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); //支持内容重新布局
        getSettings().setLoadWithOverviewMode(true);
        getSettings().setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
        getSettings().setAllowFileAccess(true); // 允许访问文件
        getSettings().setSupportZoom(true);
        getSettings().setBuiltInZoomControls(true);
        getSettings().setUseWideViewPort(true);
        getSettings().setDomStorageEnabled(true);
//        getSettings().setSupportMultipleWindows(false);
//        getSettings().setGeolocationEnabled(true);
        String cacheDirPath = context.getFilesDir().getAbsolutePath() + "cache/";
        getSettings().setAppCachePath(cacheDirPath);// 1. 设置缓存路径
        getSettings().setAppCacheMaxSize(Long.MAX_VALUE);// 2. 设置缓存大小
        getSettings().setAppCacheEnabled(true);
        getSettings().setDatabasePath(cacheDirPath);
        getSettings().setDatabaseEnabled(true);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        if (Build.VERSION.SDK_INT >= 19) {
            getSettings().setLoadsImagesAutomatically(true);
        } else {
            getSettings().setLoadsImagesAutomatically(false);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
//        setWebChromeClient(new WVChromeClient());
        setWebViewClient(new WVClient());

    }

    //进度显示
    private class WVChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (mListener != null) {
                mListener.onProgressChange(view, newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        // 全屏的时候调用
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {

            super.onShowCustomView(view, callback);

        }

        // 切换为竖屏的时候调用
        @Override
        public void onHideCustomView() {

            super.onHideCustomView();

        }
    }

    private class WVClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            if (mListener != null) {
                mListener.onPageFinish(view);
            }
            if (!getSettings().getLoadsImagesAutomatically()) {
                getSettings().setLoadsImagesAutomatically(true);
            }
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }


        @Override
        public void onReceivedError(WebView webView, int i, String s, String s1) {
            super.onReceivedError(webView, i, s, s1);
            if (mErrorListener != null) mErrorListener.onLoadError(webView);
        }

    }

    private onWebViewListener mListener;

    public void setOnWebViewListener(onWebViewListener listener) {
        this.mListener = listener;
    }

    // 进度回调接口
    public interface onWebViewListener {
        void onProgressChange(WebView view, int newProgress);

        void onPageFinish(WebView view);
    }


    private onLoadErrorListener mErrorListener;

    public void setOnLoadErrorListener(onLoadErrorListener listener) {
        this.mErrorListener = listener;
    }

    // 加载失败回调接口
    public interface onLoadErrorListener {
        void onLoadError(WebView webView);
    }

    private OnScrollChangedCallback mOnScrollChangedCallback;

    @Override
    protected void onScrollChanged(final int l, final int t, final int oldl,
                                   final int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);

        if (mOnScrollChangedCallback != null) {
            mOnScrollChangedCallback.onScroll(l - oldl, t - oldt);
        }
    }

    public void setOnScrollChangedCallback(
            final OnScrollChangedCallback onScrollChangedCallback) {
        mOnScrollChangedCallback = onScrollChangedCallback;
    }

    /**
     * Impliment in the activity/fragment/view that you want to listen to the webview
     */
    public interface OnScrollChangedCallback {
        void onScroll(int dx, int dy);
    }

}

